package com.example.lockandqueue;

import java.util.concurrent.SynchronousQueue;

/**
 * 缓存区为0的队列，必须存一个拿一个，两个同时存储的时候有一个阻塞着
 */
public class SynchronousQueueMain {

    SynchronousQueue<String> queue = new SynchronousQueue<String>();

    public SynchronousQueue<String> getQueue() {
        return queue;
    }

    public void setQueue(SynchronousQueue<String> queue) {
        this.queue = queue;
    }

    public static void main(String[] args) {
        SynchronousQueueMain synchronousQueueMain = new SynchronousQueueMain();
        SynchronousQueue<String> queue = synchronousQueueMain.getQueue();
//        boolean offer = queue.offer("11111");
//        System.out.println(offer);
//        boolean add = queue.add("222");
//        System.out.println(add);
//        String poll = queue.poll();
//        System.out.println(poll);
        synchronousQueueMain.put("1");
        System.out.println("put1");
        synchronousQueueMain.put("2");
        System.out.println("put2");

//        try {
//            Thread.sleep(4000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        synchronousQueueMain.take();
//        try {
//            Thread.sleep(2000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        synchronousQueueMain.take();


    }

    public void put(String value){
        new Thread(()->{
            try {
                queue.put(value);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void take(){
        new Thread(()->{
            String take = null;
            try {
                take = queue.take();
                System.out.println(take);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }


}
